package com.jzy.gulimall.coupon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.common.utils.PageUtils;
import com.jzy.common.utils.Query;
import com.jzy.gulimall.coupon.dao.SeckillSessionDao;
import com.jzy.gulimall.coupon.entity.SeckillSessionEntity;
import com.jzy.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.jzy.gulimall.coupon.service.SeckillSessionService;
import com.jzy.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Resource
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出最近三天的活动和关联的商品
     */
    @Override
    public List<SeckillSessionEntity> getLastThreeDaysSession() {
        //查出最近三天的活动
        List<SeckillSessionEntity> sessionEntities = baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>().between("start_time", getStartTime(), getEndTime()));
        if (CollectionUtil.isNotEmpty(sessionEntities)) {
            return sessionEntities.stream().map(item -> {
                //查询活动关联的商品
                List<SeckillSkuRelationEntity> relationEntities = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", item.getId()));
                item.setRelationEntities(relationEntities);
                return item;
            }).collect(Collectors.toList());
        }
        return null;
    }

    public String getStartTime() {
        LocalDateTime start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public String getEndTime() {
        LocalDateTime end = LocalDateTime.of(LocalDate.now().plusDays(2), LocalTime.MAX);
        return end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}